package com.framework.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.active.ActiveDao;
import com.framework.entity.flow.FlowAccount;
import com.framework.entity.flow.FlowActiv;
import com.framework.entity.flow.FlowFrozenTerminal;
import com.framework.entity.log.LogTranInfo;
import com.framework.entity.sys.SysActive;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.sys.SysAgentGrade;
import com.framework.entity.sys.SysDept;
import com.framework.entity.ter.TerMerchantReport;
import com.framework.entity.ter.TerTerminalInfo;
import com.framework.entity.ter.TerTerminalType;
import com.framework.entity.tran.TranBaoHe;
import com.framework.entity.tran.TranTransactionInfo;
import com.framework.exception.RRException;
import com.framework.exception.menu.RespCode;
import com.framework.page.PageUtils;
import com.framework.service.*;
import com.framework.service.agent.AgentIntegralService;
import com.framework.utils.DateUtils;
import com.framework.utils.string.StringUtil;
import com.framework.validator.Assert;
import com.framework.view.PurchaserView;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("activeService")
public class ActiveServiceImpl extends ServiceImpl<ActiveDao, SysActive> implements ActiveService {

    @Autowired
    private AgentService agentService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private AgentGradeService agentGradeService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private TerminalTypeService terminalTypeService;
    @Autowired
    private TerminalInfoService terminalInfoService;
    @Autowired
    private FlowActivService flowActivService;
    @Autowired
    private FlowAccountService flowAccountService;
    @Autowired
    private BaoHeService baoHeService;
    @Autowired
    private TransactionInfoService transactionInfoService;

    @Autowired
    private TerFlowInfoService terFlowInfoService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private FlowFrozenTerminalService flowFrozenTerminalService;

    @Autowired
    private AgentIntegralService agentIntegralService;





    @Override
    public Map<String, Object> queryActiveInfoList(String token) {
        Map<String, Object> map = new HashedMap();
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        //查询代理商等级
        SysAgentGrade agentGrade = agentGradeService.queryGradeByAgentId(agentId);
        if (agentGrade == null) {
            throw new RRException("9000", "未查询到代理商等级");
        }
        //进行中的活动
        List<Map<String, Object>> runningActList = baseMapper.runningActList(agentGrade.getThisGrade());
        map.put("runningActList", runningActList);
        //历史活动,查询是否参加过活动
        List<Map<String, Object>> hisList = new ArrayList<>();
        List<String> list = baseMapper.queryHistoryTimeList(agentId);
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> hisMap = new HashedMap();
            String time = list.get(i);
            BigDecimal dayAllSum = baseMapper.queryParInHistorySum(agentId, time);
            List<Map<String, Object>> dayAllList = baseMapper.queryParInHistoryLis(agentId, time);
            hisMap.put("dayAllSum", dayAllSum);
            hisMap.put("dayAllList", dayAllList);
            hisList.add(i, hisMap);
        }
        //添加了是记录
        map.put("hisList", hisList);
        return map;
    }

    @Override
    public Map<String, Object> queryRunningActiveInfo(String token, Long id, Integer type) {
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        if (agent == null) {
            throw new RRException("9000", "未查询到代理商信息");
        }
        //查询代理商等级
        SysAgentGrade agentGrade = agentGradeService.queryGradeByAgentId(agentId);
        if (agentGrade == null) {
            throw new RRException("9000", "未查询到代理商等级");
        }
        //Banner图点进来查询活动
        if (type != null) {
            //进行中的活动
            Map<String, Object> map = baseMapper.runningActInfo(agentGrade.getThisGrade(), type);
            if (map == null) {
                throw new RRException("9000", "您没有权限参加此活动");
            }
            //判断是否可以参加新手活动
            if (type == 3) {
                //活动的开始时间
                Long startDateStr = (Long) map.get("startDateStr");
                //代理商录入的时间
                Long createTime = agent.getCreateTime().getTime();
                if (createTime + 86400000 * 7 < startDateStr) {
                    throw new RRException("9000", "您没有权限参加此活动");
                }
            }
            id = (Long) map.get("id");
        }
        Map<String, Object> map = baseMapper.queryRunActiveInfo(id);
        if (map == null) {
            throw new RRException("9000", "活动错误，未查询到活动信息");
        }
        return map;
    }

    @Override
    public Map<String, Object> queryHistoryActiveInfo(String token, Long id) {
        if (id == null) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysAgent agent = agentService.queryAgentByToken(token);
        Long agentId = agent.getAgentId();
        Map<String, Object> map = baseMapper.queryHistoryActiveInfo(id, agentId);
        if (map == null) {
            throw new RRException("9000", "活动错误，未查询到活动信息");
        }
        return map;
    }

    @Override
    public List<SysActive> queryActiveList(Long deptId) {
        return this.baseMapper.queryActiveList(deptId);
    }

    @Override
    public PageUtils queryActiveTypeList(Map<String, Object> params) {
        List<SysActive> list = baseMapper.queryActiveTypeList(params);
        int totalCount = this.baseMapper.queryActiveTypeCount(params);
        int currPage = Integer.valueOf(params.get("page").toString());
        int pageSize = Integer.valueOf(params.get("limit").toString());
        PageUtils pageUtils = new PageUtils(list, totalCount, pageSize, currPage);

        return pageUtils;
    }

    @Override
    public void insertActiveType(SysActive sysActive) {
        this.baseMapper.insertActiveType(sysActive);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addActivRepCurr() {
        try {
            Integer totalNumber = 0;
            BigDecimal totalTransaction = new BigDecimal("0.00");
            //获取所有渠道信息
            List<SysDept> list = deptService.getDeptListExcept(889326L, 5L);
            for (SysDept sysDept : list) {

                //查询渠道下设置的激活返现机器类型
                List<TerTerminalType> terminalTypeList = terminalTypeService.queryIsEnableList(sysDept.getDeptId());
                for (TerTerminalType type : terminalTypeList) {
                    //需要激活的交易金额
                    BigDecimal activAmount = type.getActivAmount();
                    //终端类型
                    Integer terminalType = type.getTerminalType();
                    //根据类型查找符合的活动机器
                    List<PurchaserView> terminalList = terminalInfoService.queryActivList(terminalType, sysDept.getDeptId(), activAmount);
                    for (PurchaserView view : terminalList) {
                        //返现金额
                        BigDecimal reapAmount = view.getReapAmount();
                        //终端号
                        String sn = view.getSn();
                        //所属人
                        Long purchaserId = view.getPurchaserId();
                        //返现的时候交易金额
                        BigDecimal partAmount = view.getReapAmount();
                        //查询是否有返现记录
                        FlowActiv flowActiv = flowActivService.queryActivBySn(sn);

                        if (sysDept.getDeptId().equals(1L)) {
                            if (terminalType.intValue() == 10 || terminalType.intValue() == 11) {
                                //修改终端信息
                                terminalInfoService.activTerminal(sn);
                                agentIntegralService.addActivIntegral(sn, 1);
                                continue;
                            }
                            Integer isReport = view.getIsReport();
                            if (isReport.intValue() != 2) {
                                //修改终端信息
                                terminalInfoService.activTerminal(sn);
                                agentIntegralService.addActivIntegral(sn, 1);
                                continue;
                            }
                        }

                        if (flowActiv == null &&
                                StringUtils.isNotBlank(sn) &&
                                purchaserId != null && view.getIsOnline().intValue() == 1) {

                            totalNumber++;

                            //累计添加交易总额
                            totalTransaction = totalTransaction.add(reapAmount);
                            //修改账户余额
                            agentInfoService.addAmount(purchaserId, reapAmount);
                            //添加激活返现信息
                            String activIdSn = StringUtil.getDateString(6);
                            FlowActiv f = new FlowActiv();
                            f.setAgentId(purchaserId);
                            f.setCreateTime(new Date());
                            f.setSn(sn);
                            f.setAmount(reapAmount);
                            f.setPartAmount(partAmount);
                            f.setActivDate(new Date());
                            f.setActivId(activIdSn);
                            flowActivService.insert(f);
                            //添加流水日志
                            FlowAccount account = new FlowAccount();
                            account.setCreateTime(new Date());
                            account.setAccountType(5);
                            account.setBelId(activIdSn);
                            account.setSupportType(2);
                            account.setAmount(reapAmount);
                            account.setAgentId(purchaserId);
                            flowAccountService.insertFlowAccount(account);
                        }
                        //修改终端信息
                        terminalInfoService.activTerminal(sn);
                        agentIntegralService.addActivIntegral(sn, 1);

                        terFlowInfoService.addActivationAndReapInfo(sn, sysDept.getDeptId());
                    }
                }
            }
            //录入交易导入日志
            LogTranInfo log = new LogTranInfo();
            log.setExplainsInfo("乐刷68激活返现" + "-成功");
            log.setAccountId(new Long(0));
            log.setLogStates("SUCCESS");
            log.setTotalNumber(totalNumber);
            log.setTotalTransaction(totalTransaction);
            transactionInfoService.insertTerLog(log);

            agentIntegralService.addActivIntegral("1", 1);
            //连续激活奖励
            handleActivAmount();


        } catch (Exception e) {
            e.printStackTrace();
            transactionInfoService.insertFailTerLog("乐刷68激活返现" + "-" + e.getMessage(), 0L);
        }
    }

    private void handleActivAmount() {
        List<Map<String, Object>> list = merchantService.queryActivAgent();

        for (Map<String, Object> map : list) {
            Long agentId = (Long) map.get("agentId");
            Integer num = (Integer) map.get("num");
            //查询过往的奖励记录 ,按时间倒序
            List<FlowAccount> accountList = flowAccountService.selectList(new EntityWrapper<FlowAccount>().eq("agent_id", agentId).eq("account_type", 10)
                    .orderBy("create_time", false)
            );
            //没有记录,第一次达标
            if (accountList == null || accountList.size() == 0) {
                agentInfoService.addAmount(agentId, new BigDecimal("4000"));
                FlowAccount flowAccount = new FlowAccount();
                flowAccount.setAmount(new BigDecimal("4000"));
                flowAccount.setAgentId(agentId);
                flowAccount.setCreateTime(new Date());
                flowAccount.setRemark("基础工资奖励4000元");
                flowAccount.setSupportType(2);
                flowAccount.setAccountType(10);
                flowAccountService.insert(flowAccount);

            } else if (accountList.size() == 1 || accountList.size() == 2) {
                //获取第一条记录，判断第一条是以前的还是本月的
                FlowAccount account = accountList.get(0);

                Date date = account.getCreateTime();

                Integer accountMonth = DateUtils.getCurrMonth(date);

                Integer currMonth = DateUtils.getCurrMonth(new Date());
                //本月
                if (accountMonth.intValue() == currMonth.intValue()) {
                    continue;
                } else {
                    //是否连续 即当前比上月大1
                    if (currMonth.intValue() - accountMonth.intValue() == 1) {
                        //检查激活数量是否合格
                        //所需数量
                        int arrivalNum=30+accountList.size()*10;
                        if(num>=arrivalNum){
                            agentInfoService.addAmount(agentId, new BigDecimal("4000"));
                            FlowAccount flowAccount = new FlowAccount();
                            flowAccount.setAmount(new BigDecimal("4000"));
                            flowAccount.setAgentId(agentId);
                            flowAccount.setCreateTime(new Date());
                            flowAccount.setRemark("基础工资奖励4000元");
                            flowAccount.setSupportType(2);
                            flowAccount.setAccountType(10);
                            flowAccountService.insert(flowAccount);
                        }


                    }
                }

            }

        }


    }

    @Override
    public boolean handleTlActiv(PurchaserView purchaserView, Long deptId) {
        if (!deptId.equals(5L)) {
            return true;
        }

        String sn = purchaserView.getSn();

        TerMerchantReport report = merchantService.queryMerchantBySn(sn);

        SysAgent agent = agentService.queryAgentById(report.getAgentId());

        report.setMerchantName(Assert.hasSpace(report.getMerchantName()));

        report.setPhone(Assert.hasSpace(report.getPhone()));

        if (StringUtils.equals(report.getMerchantName(), agent.getName()) && StringUtils.equals(report.getPhone(), agent.getPhone())) {

            FlowFrozenTerminal ter = flowFrozenTerminalService.selectOne(new EntityWrapper<FlowFrozenTerminal>().eq("sn", purchaserView.getSn()));
            if (ter != null) {
                return true;
            }

            FlowFrozenTerminal ter2 = flowFrozenTerminalService.selectOne(new EntityWrapper<FlowFrozenTerminal>().eq("agent_id", agent.getAgentId()));
            if (ter2 != null) {
                return true;
            }

            BigDecimal frozen = new BigDecimal("3000.00");
            //添加冻结资金
            agentInfoService.addFrozen(agent.getAgentId(), frozen);

            //添加冻结记录
            FlowFrozenTerminal info = new FlowFrozenTerminal();
            info.setAgentId(agent.getAgentId());
            info.setAmount(frozen);
            info.setDeptId(deptId);
            info.setSn(purchaserView.getSn());
            info.setCreateTime(new Date());
            flowFrozenTerminalService.insert(info);

            terminalInfoService.activTerminal(purchaserView.getSn());

            agent.setStandardState(1);
            agentService.updateById(agent);

            //给上级返现

            FlowFrozenTerminal terminal = flowFrozenTerminalService.selectOne(
                    new EntityWrapper<FlowFrozenTerminal>()
                            .eq("agent_id", agent.getPid()));
            //如果一级合伙人自身没有冻结记录，则不享有100块钱的奖励
            if (terminal == null) {
                return true;
            }
            BigDecimal recAmount = new BigDecimal("100");
            agentInfoService.addAmount(agent.getPid(), recAmount);
            FlowAccount flowAccount = new FlowAccount();
            flowAccount.setAmount(recAmount);
            flowAccount.setAccountType(11);
            flowAccount.setSupportType(2);
            flowAccount.setBelId(purchaserView.getSn());
            flowAccount.setCreateTime(new Date());
            flowAccount.setAgentId(agent.getPid());
            flowAccount.setRemark("推荐" + agent.getName() + "奖励");
            flowAccountService.insert(flowAccount);
            return true;
        } else {
            return false;
        }


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addActivRepShuaBao() {
        //类型为6的拉卡拉宝盒
        List<Map<String, Object>> list = baoHeService.queryBaoHeReturnList();
        for (int i = 0; i < list.size(); i++) {
            //所属终端号
            String sn = (String) list.get(i).get("sn");
            //代理商id
            Long agentId = (Long) list.get(i).get("agentId");
            BigDecimal amount = new BigDecimal("80");
            //d查询是否有返现记录
            boolean isRep = baoHeService.isThisMonthReq(sn);
            if (isRep) {
                //修改账户余额
                agentInfoService.addAmount(agentId, amount);
                //添加激活返现信息
                String activIdNo = StringUtil.getDateString(6);
                TranBaoHe f = new TranBaoHe();
                f.setAgentId(agentId);
                f.setBaoHeId(activIdNo);
                f.setReturnDate(new Date());
                f.setCreateTime(new Date());
                f.setSn(sn);
                f.setAmount(amount);
                baoHeService.insert(f);
                //添加流水日志
                FlowAccount account = new FlowAccount();
                account.setCreateTime(new Date());
                account.setAccountType(9);
                account.setBelId(activIdNo);
                account.setSupportType(2);
                account.setAmount(amount);
                account.setAgentId(agentId);
                flowAccountService.insertFlowAccount(account);
            }
        }
    }

    @Override
    public SysActive queryActiveById(Long activeId) {
        return this.baseMapper.queryActiveById(activeId);
    }

    @Override
    public void updateActiveById(SysActive sysActive) {
        this.baseMapper.updateActiveById(sysActive);
    }

}
